import globalConfig from '@/config'

/**
 * 随机从数据中选取n项元素
 */
export const getRandomArrayElements = (arr, count) => {
	var shuffled = arr.slice(0),
		i = arr.length,
		min = i - count,
		temp, index
	while (i-- > min) {
		index = Math.floor((i + 1) * Math.random())
		temp = shuffled[index]
		shuffled[index] = shuffled[i]
		shuffled[i] = temp
	}
	return shuffled.slice(min)
}

export const formatArr = (segmentType, sep = '/') => {
	let result = ''
	if (segmentType) {
		try {
			const segmentArr = JSON.parse(segmentType)
			segmentArr.forEach(item => {
				result += item + sep
			})
		} catch (error) {
			return segmentType
		}
	}
	if (result) {
		let len = sep.length > 1 ? 2 : 1
		result = result.substring(0, result.length - len)
	}
	return result
}
export const formatProjectType = pt => {
	if (!pt) {
		return ''
	}
	if (pt.indexOf('工程施工') !== -1) {
		return 'build.png'
	} else if (pt.indexOf('采购') !== -1) {
		return 'purchase.png'
	} else if (pt.indexOf('软件研发') !== -1) {
		return 'asset.png'
	} else if (pt.indexOf('系统集成') !== -1) {
		return 'land.png'
	}
	return ''
}
// 格式化附件json字符串
export const formatJsonStr = attaJsonStr => {
	if (attaJsonStr && attaJsonStr.length > 0) {
		try {
			return JSON.parse(attaJsonStr)
		} catch (e) {
			return []
		}
	}
	return []
}

export const formatAuditStatus = status => {
	let text = ''
	let color = ''
	switch (status) {
		case '-1':
			;
			(() => {
				text = '未提交'
				color = 'primary'
			})()
			break
		case '0':
			;
			(() => {
				text = '不通过'
				color = 'error'
			})()
			break
		case '1':
			;
			(() => {
				text = '通过'
				color = 'success'
			})()
			break
		default:
			;
			(() => {
				text = '待审核'
				color = 'warning'
			})()
			break
	}
	return {
		color,
		text
	}
}

export const formatStatus = status => {
	let text = ''
	let color = ''
	switch (status) {
		case '预录完成':
			;
			(() => {
				text = '预录完成'
				color = 'primary'
			})()
			break
		case '作废':
			;
			(() => {
				text = '作废'
				color = 'error'
			})()
			break
		case '已入库':
			;
			(() => {
				text = '已入库'
				color = 'success'
			})()
			break
		default:
			;
			(() => {
				text = status
				color = 'warning'
			})()
			break
	}
	return {
		color,
		text
	}
}

/**
 * 附件预览
 * @param {Object} atta附件{name:'',url:''}
 */
export const filePreview = atta => {
	let name = atta.name
	let url = atta.url
	// 判断文件类型
	if (url && typeof url === 'string') {
		let index = url.lastIndexOf('.')
		let suffix = url.substring(index + 1)
		if (suffix) {
			suffix = suffix.toLowerCase()
			switch (suffix) {
				case 'pdf':
				case 'doc':
				case 'docx':
				case 'xls':
				case 'xlsx':
				case 'ppt':
				case 'pptx':
					// 转换为pdf进行预览
					uni.redirectTo({
						url: '/pages/file/file-preview?name=' + name + '&url=' + url
					})
					break
				case 'jpg':
				case 'jpeg':
				case 'png':
				case 'bmp':
				case 'gif':
					// 预览图片
					uni.previewImage({
						urls: [globalConfig.fileAddr + url],
						longPressActions: {
							itemList: ['发送给朋友', '保存图片', '收藏'],
							success: function(data) {
								console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
							},
							fail: function(err) {
								console.log(err.errMsg);
							}
						}
					})
					break
			}
		}
	}
}

/**
 * 返回日期区间起止数组, sample ['2020-1-1','2020-5-1']
 */
export const getDateRange = (dateNow, intervalDays, bolPastTime) => {
  const oneDayTime = 24 * 60 * 60 * 1000
  const list = []
  let lastDay

  if (bolPastTime === true) {
    lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime)
    list.push(formateDate(lastDay))
    list.push(formateDate(dateNow))
  } else {
    lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime)
    list.push(formateDate(dateNow))
    list.push(formateDate(lastDay))
  }
  return list
}

const formateDate = (time) => {
  const year = time.getFullYear()
  let month = time.getMonth() + 1
  let day = time.getDate()

  if (month < 10) {
    month = '0' + month
  }

  if (day < 10) {
    day = '0' + day
  }
  return year + '-' + month + '-' + day + ''
}

/*'yyyy-MM-dd'格式的字符串转日期*/

export const stringToDate = (str) => {

    var tempStrs = str.split(' ')

    var dateStrs = tempStrs[0].split('-')

    var year = parseInt(dateStrs[0], 10)

    var month = parseInt(dateStrs[1], 10) - 1

    var day = parseInt(dateStrs[2], 10)

    // var timeStrs = tempStrs[1].split(":");

    // var hour = parseInt(timeStrs [0], 10);

    // var minute = parseInt(timeStrs[1], 10);

    // var second = parseInt(timeStrs[2], 10);

    // var date = new Date(year, month, day, hour, minute, second);
	
	var date = new Date(year, month, day, 0, 0, 0)

    return date

}

/*华凌-安赛乐，涟钢*/
const getHualing = (code) => {
  if(code && code.indexOf('钢卷号') > -1 && code.startsWith('防伪码')){
	const start = code.indexOf('钢卷号') + 4
	const end = start + 10
  	return code.slice(start, end)
  }
}

/*本钢*/
const getBengang = (code) => {
  if(code && code.indexOf('卷号') > -1 && code.startsWith('：本钢')){
	const start = code.indexOf('卷号') + 3
	const end = start + 13
  	return code.slice(start, end)
  }
}

/*鞍钢股份*/
const getAngang = (code) => {
  if(code && code.indexOf('卷号') > -1 && code.startsWith('鞍钢')){
	const start = code.indexOf('卷号') + 3
	const end = start + 14
  	return code.slice(start, end)
  }
}

/*获取钢卷号,不同的厂家二维码不一样*/

export const getScanCode = (scanCode) => {

    let code = getHualing(scanCode)

    if(code) {
		return code
	}
	
	code = getBengang(scanCode)
	
	if(code) {
		return code
	}
	
	code = getAngang(scanCode)
	
	if(code) {
		return code
	}
		
    return scanCode
}
